package com.example.weight.wormHandle.garbageDisposal.onsiteDispose;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WormSaling extends AppCompatActivity {
    private String name, factory;
    private TitleBar titleBar;
    //销售日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date salingDate = new Date(System.currentTimeMillis());
    private TextView worm_saling_exportDate;
    private TextView insect_export_weight;
    private TextView insect_dung_export_weight;
    private TextView companyName;
    private TextView contacter;
    private TextView telephone;
    private TextView yongfa;
    private TextView feedback;
    private TextView remark;
    String activeButton = new String();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.worm_saling);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                WormSaling.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });


        worm_saling_exportDate = findViewById(R.id.worm_saling_exportDate);
        worm_saling_exportDate.setText(simpleDateFormat.format(salingDate));

        /**
         *2个重量
         */
        //成虫外销重量
        insect_export_weight = findViewById(R.id.insect_export_weight);
        //虫粪外销重量
        insect_dung_export_weight = findViewById(R.id.insect_dung_export_weight);
        companyName = findViewById(R.id.company_name);
        contacter = findViewById(R.id.contacter);
        telephone = findViewById(R.id.telephone);
        yongfa = findViewById(R.id.use);
//        feedback = findViewById(R.id.feedback);
        remark = findViewById(R.id.worm_saling_remark);
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/kitchenwaste/export/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy",response.toString());
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")) {
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    worm_saling_exportDate.setText(data.getString("exportDate"));
                                    insect_export_weight.setText(data.getString("insectExportWeight"));
                                    insect_dung_export_weight.setText(data.getString("insectDungExportWeight"));
                                    companyName.setText(data.getString("companyName"));
                                    contacter.setText(data.getString("contacter"));
                                    telephone.setText(data.getString("telephone"));
                                    yongfa.setText(data.getString("yongfa"));
//                                    feedback.setText(data.getString("feedback"));
                                    remark.setText(data.getString("remark"));
                                    Toast.makeText(WormSaling.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(WormSaling.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "insect_export_weight_btn":
                insect_export_weight.setText(weight);
                break;
            case "insect_dung_export_weight_btn":
                insect_dung_export_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.insect_export_weight_btn:
                activeButton = "insect_export_weight_btn";
                break;
            case R.id.insect_dung_export_weight_btn:
                activeButton = "insect_dung_export_weight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(WormSaling.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
    public void save(View view) {
        if (insect_export_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写成虫外销重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (insect_dung_export_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写虫粪外销重量", Toast.LENGTH_SHORT).show();
            return;
        }

        if (((TextView) findViewById(R.id.company_name)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写公司名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if ( ((TextView) findViewById(R.id.contacter)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (((TextView) findViewById(R.id.telephone)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写联系电话", Toast.LENGTH_SHORT).show();
            return;
        }
        if (((TextView) findViewById(R.id.use)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写用途", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (((TextView) findViewById(R.id.feedback)).getText().toString().equals("")) {
//            Toast.makeText(this, "请填写效果反馈", Toast.LENGTH_SHORT).show();
//            return;
//        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/kitchenwaste/export/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    if (response.toString().equals("true"))
                                        Toast.makeText(WormSaling.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(WormSaling.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(WormSaling.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("exportDate", simpleDateFormat.format(salingDate));
                            map.put("insectExportWeight", insect_export_weight.getText().toString());
                            map.put("insectDungExportWeight",insect_dung_export_weight.getText().toString());
                            map.put("companyName", ((TextView) findViewById(R.id.company_name)).getText().toString());
                            map.put("contacter", ((TextView) findViewById(R.id.contacter)).getText().toString());
                            map.put("telephone", ((TextView) findViewById(R.id.telephone)).getText().toString());
                            map.put("yongfa", ((TextView) findViewById(R.id.use)).getText().toString());
                            map.put("feedback", "");
                            map.put("remark", ((TextView) findViewById(R.id.worm_saling_remark)).getText().toString());
                            map.put("recorder",name);
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}
